<?php
namespace LP\tools;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/3/18
 * Time: 11:55
 */
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
class Helper
{
    /**
     * 用于模板中来检测连接显不显示
     * @param $route
     * @return bool
     */
    public static function checkPermission($route)
    {
        if(Auth::guard('admin')->user()->is_super || Auth::guard('admin')->user()->can($route)){
            return true;
        }else{
            return false;
        }
    }

    public static function response($data = array(),$code = INFO_SUCCESS_CODE, $msg = INFO_SUCCESS_MSG){
        $res = array('code'=>$code,'msg'=>$msg,'info'=>$data);
        return $res;
    }

    public static function upload(Request $request,$file_field,$is_rand = true,$extension =['png,jpg,gif,jpeg'] ,$path='uploads',$filename='')
    {
        $res = array('status'=>true,'info'=>'上传成功','data'=>[]);
        $file = $request->file($file_field);
        if($file->isValid()){
            //检验一下上传的文件是否有效.
            $clientName = $file->getClientOriginalName();
            $tmpName = $file->getFileName(); // 缓存在tmp文件夹中的文件名
            $realPath = $file->getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径

            //这里要注意,如果我使用接下来的move方法之后, getRealPath() 就找不到文件的路径了.因为文件已经被移走了.

            $entension = $file->getClientOriginalExtension(); //上传文件的后缀.

//            if(is_string($extension)){
//                if(strtolower($entension) != strtolower($extension) ){
//                    $res['status'] = false;
//                    $res['info'] = '文件后缀只允许是'.implode(',',$extension);
//                    return $res;
//                }
//            }
//            if(is_array($extension)){
//                if(!in_array(strtolower($entension),array_map('strtolower',$extension))){
//                    $res['status'] = false;
//                    $res['info'] = '文件后缀只允许是'.implode(',',$extension);
//                    return $res;
//                }
//            }

//            $mimeTye = $file->getMimeType();//获取mime类型

            $originName = $file->getClientOriginalName(); //获取文件文件名称

            if($is_rand){
                $filename = date('YmdHis').rand(1000,999).'.'.$entension;
            }else{
                if($filename){
                    $filename = $filename.'.'.$entension;
                }else{
                    $filename = $originName;
                }
            }
            //$path = public_path().'/'.trim($path,' /');
            $file->move($path,$filename);
            $res['data']['filename'] = $filename;
            $res['data']['path'] = $path;
            $res['data']['original_name'] = $clientName;

        }else{
            $res['info'] = '非法操作';
            $res['status'] = false;
        }
        return $res;
    }

    public static function chunkUpload($file_field,$is_rand = true,$extension =['png,jpg,gif,jpeg,mp4,avi'] ,$path='uploads',$filename='')
    {
        $res = array('status'=>true,'info'=>'上传成功','data'=>[]);
        if(!$file_field){
            $res['status'] = false;
            $res['info'] = '函数调用方法不对,请传入file字段';
            return $res;
        }
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $targetDir = trim($path,"/")."_tmp";
        $uploadDir = trim($path,"/");
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES[$file_field]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        $clientName = $fileName;
        //获取文件后缀

        $entension = pathinfo($fileName, PATHINFO_EXTENSION);

//        if(is_string($extension)){
//                if(strtolower($entension) != strtolower($extension) ){
//                    $res['status'] = false;
//                    $res['info'] = '文件后缀只允许是'.implode(',',$extension);
//                    return $res;
//                }
//            }
//        if(is_array($extension)){
//            if(!in_array(strtolower($entension),array_map('strtolower',$extension))){
//                $res['status'] = false;
//                $res['info'] = '文件后缀只允许是'.implode(',',$extension);
//                return $res;
//            }
//        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                $res['status'] = false;
                $res['info'] = '打开临时文件夹失败';
                return $res;
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            $res['status'] = false;
            $res['info'] = '打开读取输出流失败!';
            return $res;
        }
        if (!empty($_FILES)) {
            if ($_FILES[$file_field]["error"] || !is_uploaded_file($_FILES[$file_field]["tmp_name"])) {
                $res['status'] = false;
                $res['info'] = '移动上传文件失败!';
                return $res;
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES[$file_field]["tmp_name"], "rb")) {
                $res['status'] = false;
                $res['info'] = '读取读取输入流失败!';
                return $res;
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                $res['status'] = false;
                $res['info'] = '读取读取输入流失败!';
                return $res;
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            //注意自定义文件名 一定要在这里面操作
            if($is_rand){
                $filename = date('YmdHis').rand(1000,999).'.'.$entension;
            }else{
                if($filename){
                    $filename = $filename.'.'.$entension;
                }else{
                    $filename = $fileName;
                }
            }
            $fileName = $filename;
            $uploadPath = trim($path,'/')."/".$filename;

            if (!$out = @fopen($uploadPath, "wb")) {
                $res['status'] = false;
                $res['info'] = '打开读取输出流失败!';
                return $res;
            }
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        $res['data']['filename'] = $fileName;
        $res['data']['path'] = $path;
        $res['data']['original_name'] = $clientName;
        return $res;

    }

}